package com.dlc.shop.seckill.platform.task;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Lists;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.dlc.shop.bean.enums.EsOperationType;
import com.dlc.shop.bean.event.EsProductUpdateEvent;
import com.dlc.shop.seckill.common.model.Seckill;
import com.dlc.shop.seckill.common.service.SeckillCacheManager;
import com.dlc.shop.seckill.common.service.SeckillOrderService;
import com.dlc.shop.seckill.common.service.SeckillService;
import com.dlc.shop.seckill.common.service.SeckillSkuService;
import com.dlc.shop.service.ProductService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;


/**
 * 秒杀订单的定时任务
 * @author LGH
 */
@Slf4j
@Component
@AllArgsConstructor
public class SeckillOrderTask {

    private final SeckillOrderService seckillOrderService;
    private final SeckillSkuService seckillSkuService;
    private final SeckillService seckillService;
    private final ProductService productService;
    private final ApplicationEventPublisher eventPublisher;
    private final SeckillCacheManager seckillCacheManager;

    /**
     * 取消订单
     */
    @XxlJob("cancelSeckillOrder")
    public void cancelSeckillOrder() {
        log.info("解锁订单创建失败的秒杀库存。。。");
        seckillCacheManager.unLockFailOrderStock();

        log.info("取消超时未支付的秒杀订单...");
        seckillOrderService.cancelOrderUnpayOrderByTime();
    }

    /**
     * 秒杀结束，改变商品类型
     */
    @XxlJob("seckillFinish")
    public void seckillFinish(){
        List<Seckill> seckillList = seckillService.list(new LambdaQueryWrapper<Seckill>()
                .lt(Seckill::getEndTime, new Date())
                .ne(Seckill::getStatus, 0)
                .ne(Seckill::getIsDelete, 1)
        );
        if (CollectionUtils.isEmpty(seckillList)) {
            return;
        }
        List<Long> seckillIds = Lists.newArrayList();
        List<Long> prodIds = Lists.newArrayList();
        for (Seckill seckill: seckillList) {
            seckillIds.add(seckill.getSeckillId());
            prodIds.add(seckill.getProdId());
        }
        if (CollUtil.isNotEmpty(seckillIds)){
            // 改变商品类型
            seckillService.changeProdTypeBySeckillIdList(seckillIds);
        }
        eventPublisher.publishEvent(new EsProductUpdateEvent(null, prodIds, EsOperationType.SAVE_BATCH));
        // 清除缓存
        for (Long seckillId : seckillIds) {
            seckillSkuService.removeSeckillSkuCacheBySeckillId(seckillId);
        }
        seckillService.batchRemoveSeckillCache(seckillIds, prodIds);
        for (Long prodId : prodIds) {
            productService.removeProdCacheByProdId(prodId);
        }
    }
}
